import { defineStore } from 'pinia'
import { getCrawlerStatus, startCrawler, stopCrawler } from '../api/crawler'

export const useCrawlerStore = defineStore('crawler', {
  state: () => ({
    isLoading: false,
    status: {
      isRunning: false,
      pid: null,
      lastStartTime: null
    }
  }),
  actions: {
    async fetchStatus() {
      try {
        const res = await getCrawlerStatus()
        this.status = res.data  // 直接赋值data对象
      } catch (error) {
        console.error('获取状态失败:', error)
        throw error
      }
    },
    async start() {
      this.isLoading = true
      try {
        await startCrawler()
        await this.fetchStatus()  // 重新获取最新状态
      } finally {
        this.isLoading = false
      }
    },
    async stop() {
      this.isLoading = true
      try {
        await stopCrawler()
        await this.fetchStatus()
      } finally {
        this.isLoading = false
      }
    }
  }
})